<?php
class ModelAccountValidate extends Model {
	public function addValidate($data) {
		$this->db->query("INSERT INTO " . DB_PREFIX . "validate_code SET customer_id = '" . (int)$data['customer_id'] . "',validate_type = '" . (int)$data['validate_type'] . "', code = '" . $this->db->escape($data['code']) . "', code_md5 = '" . $this->db->escape($data['code_md5']) . "', validate_data = '" . $this->db->escape($data['validate_data']) . "', date_expire = DATE_ADD(NOW(),INTERVAL '" . $this->db->escape($data['date_expire']) . "' SECOND), date_added = NOW(), date_updated = NOW()");
	}

	public function getValidateByCode($code,$validate_type) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "validate_code WHERE status = 1 AND validate_type = '". (int)$validate_type  ."' AND date_expire > NOW() AND ( code = '" . $this->db->escape($code) . "' or code_md5= '" . $this->db->escape($code) . "')");
		
		return $query->row;
	}
	
	public function getValidateByCodeAndData($code,$data,$validate_type) {
	    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "validate_code WHERE status = 1 AND customer_id='".(int)$this->customer->getId()."' AND validate_type = '". (int)$validate_type  ."' AND date_expire > NOW() AND ( code = '" . $this->db->escape($code) . "' or code_md5= '" . $this->db->escape($code) . "') AND validate_data = '".$this->db->escape($data)."'");
	
	    return $query->row;
	}

	public function useValidateCode($code, $customer_id, $validate_type) {
		$query = $this->db->query("UPDATE " . DB_PREFIX . "validate_code SET status = 0 WHERE  status = 1 AND validate_type = '". (int)$validate_type  ."' AND customer_id = '". $customer_id ."' AND (code = '" . $this->db->escape($code) . "' OR code_md5= '" . $this->db->escape($code) . "')");
		
		return $query->row;
	}
	
	public function makeValidateCode($num)
	{
	    $code = "";
	    for ($i = 0; $i < $num; $i++) {
	        $code .= rand(0, 9);
	    }
	    $code_md5 = md5($code);
	    return array(
	      'code'=>$code,
	      'code_md5'=>  $code_md5
	    );
	}
}
?>